<template>
  <upload-excel :on-success="handleSuccess" />
</template>

<script>
import { importEmployee, getEmployeeList } from '@/api/employees'
export default {
  name: 'Import',
  data() {
    return {
      type: this.$route.query.type,
      total: 1,
      list: []
    }
  },
  created() {
    this.getEmployeeList()
  },
  methods: {
    async getEmployeeList() {
      const { total, rows } = await getEmployeeList({
        page: 1,
        size: this.total
      })
      this.total = total
      this.list = rows
    },
    handleSuccess({ header, results }) {
      if (this.type === 'user') {
        this.importUser(results)
      }
    },
    // async importUser(results) {
    //   const userRelations = {
    //     入职日期: 'timeOfEntry',
    //     手机号: 'mobile',
    //     姓名: 'username',
    //     转正日期: 'correctionTime',
    //     工号: 'workNumber'
    //   }
    //   const arr = []
    //   results.forEach(item => {
    //     const userInfo = {}
    //     for (const key in item) {
    //       const englishKey = userRelations[key]
    //       if (englishKey === 'timeOfEntry' || englishKey === 'correctionTime') {
    //         userInfo[englishKey] = new Date(this.formatDate(item[key], '/'))
    //       } else {
    //         userInfo[userRelations[key]] = item[key]
    //       }
    //     }
    //     arr.push(userInfo)
    //   })
    //   await importEmployee(arr)
    //   this.$router.back()
    // },
    async importUser(results) {
      const userRelations = {
        入职日期: 'timeOfEntry',
        手机号: 'mobile',
        姓名: 'username',
        转正日期: 'correctionTime',
        工号: 'workNumber'
      }

      // 获取员工信息
      await this.getEmployeeList()

      const arr = []
      results.forEach(item => {
        const userInfo = {}
        for (const key in item) {
          const englishKey = userRelations[key]
          if (englishKey === 'timeOfEntry' || englishKey === 'correctionTime') {
            userInfo[englishKey] = new Date(this.formatDate(item[key], '/'))
          } else {
            userInfo[userRelations[key]] = item[key]
          }
        }

        for (let i = 0; i < this.list.length; i++) {
          if (+userInfo.mobile === +this.list[i].mobile) { return }
        }
        // console.log(userInfo.mobile)
        arr.push(userInfo)
      })

      if (arr.length) {
        await importEmployee(arr)
        this.$message.success('导入成功! ')
        this.$router.back()
      } else {
        this.$message.info('当前导入数据全部存在库中,无需导入! ')
      }
    },
    formatDate(numb, format) {
      const old = numb - 1
      const t = Math.round((old - Math.floor(old)) * 24 * 60 * 60)
      const time = new Date(1900, 0, old, 0, 0, t)
      const year = time.getFullYear()
      const month = time.getMonth() + 1
      const date = time.getDate()
      return year + format + (month < 10 ? '0' + month : month) + format + (date < 10 ? '0' + date : date)
    }
  }
}
</script>

